var stamp = 0, defwdt = 160, playing = false, panes = [], gateway, boxes, db = [];  
var onSize = {
    list   : [],
    add    : function (i) {if (i) this.list.push (i);},
    invoke : function () {for (var x=0;x<this.list.length;x++) 
    	                    {
    	                    	try
    	                    	{
    	                    		this.list[x].invoke(); 
    	                    	} catch (ex) { } 
    	                    }
    },
    clear  : function () { this.list = [] }
}

function S4() {
   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}

function guid() {
   return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

function donext(i)
{
	var box = $C('drp'), index = box.selectedIndex;
	index += i;
	box.selectedIndex = index;
	location.href=box.className+box.options[box.selectedIndex].value;
}

function advance(i)
{
	var box = $C('drp'), index = box.selectedIndex;
	index += i;
	box.selectedIndex = index;
	view (box.options[box.selectedIndex].value);
}

function Play(go)
{
	playing = !playing;
	if (playing)
	{
		$C('btn').value = 'Stop';
		advance(1);
		return;
	}
	$C('btn').value = 'Play';
}



function attach ()
{
	gateway = new Image();
	var picture=$C('box'), bar=$C('controlbar'), drop=$C('drp');
	if (picture)
	{
		picture.invoke = function ()
		{  
		    var o       = { w:window.innerWidth,h:window.innerHeight };   
		    var ro = o.w / o.h, ri = this.width / this.height, ok = (ro > 1 && ri > 1) || (ro <= 1 && ri <= 1);
		    sz = ratio(this, (ok?Math.max(o.w,o.h):Math.min(o.w,o.h)) - 180);
		   
	        this.width  = sz.x;
	        this.style.height = sz.y + 'px'; 
		}	 
		onSize.add (picture);
	}
	if (drop)
	{
		drop.invoke = function ()
		{
		    var o       = { w:window.innerWidth - 200};    
		    this.style.width = o.w + 'px'; 
		}
		onSize.add(drop);
	}
	if (bar)
	{ 
		bar.invoke = function ()
		{
		    this.style.display = 'inline';
		    var o       = { x:0,y:window.innerHeight - this.offsetHeight, w:picture.offsetWidth };   
		    this.style.top     = o.y + 'px';
		    this.style.left    = o.x + 'px'; 
		    this.style.width   = o.w + 'px'; 
		}
		onSize.add(bar);
	}
	window.onresize = function ()
	{
	    onSize.invoke ();
	} 
    onSize.invoke ();
    enqueue();
}

function $C(i) { return document.getElementById(i); };
function ratio(im,spec)
{
    var w=im.width,h=im.height,r=w/h,d=spec||defwdt;
	return w>h?{x:d,y:d/r}:{y:d,x:d*r}
}

function preload (im, src)
{
	var that=im,bg = new Image();
	var r=Math.random()*100;
	bg.onload = function ()
	{
		that.onload = null;
		var sz = ratio (this);
		that.width  = sz.x;
		that.height = sz.y;
		that.src = this.src;
		that.style.border="solid 1px";
		that.style.borderColor = 'white gray gray white'
	}
	im.style.border="solid 1px cyan";    
	bg.src = src + '?' + r;
} 

function view (src)
{ 
    var im = $C('box'); //, pic = new Image(); 
	function foo () { advance(1); } 
	  
	gateway.onload = function ()
	{ 
	    var o       = { w:window.innerWidth,h:window.innerHeight };   
	    var ro = o.w / o.h, ri = this.width / this.height, ok = (ro > 1 && ri > 1) || (ro <= 1 && ri <= 1);
	    sz = ratio(this, (ok?Math.max(o.w,o.h):Math.min(o.w,o.h)) - 80);
		im.style.border="solid 1px yellow";  
		im.onload = function () 
		{
		    im.width  = sz.x;
			im.height = sz.y;
			this.style.border="solid 1px lime";  
			if (playing) setTimeout (foo, 5000);
	    }
		im.src    = this.src;
	} 
	gateway.onerror = function ()
	{
	    im.style.border="solid 1px red"; 
		foo();
	} 

	im.style.border="solid 1px cyan";    
	gateway.src = src;  
}



function download (url, info)
{
	var array = info.split(',');
	var index = array[0];
	var src   = array[1];
	var uri   = url + index + "/request/download";
	var check = url + index + "/request/status"; 
	var ping = function ()
	{ 
		var pong = load (check);
		if (pong == 'OK')
		{ 
			document.title =  "SuperNET - " + src;
			var go = function () { $C('box').src = src; }
			setTimeout (go, 250);
			return;
		}
		document.title = "Pinging..." + pong;
		setTimeout (ping, 5000);
	}
	
	var begin = function ()
	{
		document.title = "Connecting...";
		load (uri);
		ping();
	}
	setTimeout(begin, 500);
}

function load(uri)
{    
    var mhttp=XmlHttp.create();                                                                                                                                                                                                                                                                   
    mhttp.open("GET", uri, false);     
    mhttp.send();     

    return mhttp.responseText;
}

function monitor(address, after)
{     
	var repeat=function () { reping (address, after) }
	setTimeout (repeat, 1)
}

var queue=[], q = 0, qt = null, conn = null;
function enqueue()
{    
	if (qt) clearTimeout(qt);
	if (!queue.length) return;
	var my  = queue[q];
	var uri = '/ui/queue/id/' + my;
	if (!conn) conn=XmlHttp.create();                                                                                                                                                                                                                                                                   
    conn.open("GET", uri , true);      
    conn.onreadystatechange = function () 
    { 
    	if (conn.readyState != 4) return;
        var ok = conn.responseText; 
        if (ok=='OK')
        {
        	var tmp = [];
        	for (var x=0;x<queue.length;x++)
        		if(queue[x] != my)
        			tmp.push (queue[x]);
        	queue = tmp;
        	document.title = 'Encoding complete!'; 
        }
        
        if ($(my)) $(my).innerHTML = bebar(ok);
        else document.title = ok;
    	qt = setTimeout(enqueue, 3000); 
    }        
	conn.send();
	q++;
	if (q>=queue.length) q = 0;
}

function bebar(str)
{
	var x, f=function(i) { return "<font color='royalblue'>"+i+"</font>" }, b='';
	if (re=/(\d+)\%/.exec (str))
	{
		var m = str.length * (re[1] / 100);
		for (var i=0;i<str.length;i++) 
        {
			x = str.substr(i, 1);
			b += i < m ? f(x) : x;
		}
		return '<u>' + b + '</u>';
	}
	return str;
}

function reping(address, after)
{    
	var URL=after, URI=address, r=Math.random()*100;
	var repeat=function () { reping (URI, URL) }
    var connection=XmlHttp.create();                                                                                                                                                                                                                                                                   
    connection.open("GET", URI , true);      
    
    connection.onreadystatechange = function ()                                              
    {                                             
        if (connection.readyState == 4)                                              
        {           
            var result = connection.responseText; 
            if (result=="OK") 
            {
                location.href = URL;
                return;
            }  
            setTimeout(repeat, 500);                    
        }  
    }               
    var blank = "http://www.101stratford.com/webservices/images/clear.gif";
    var image = "/data/progress.jpeg";
    var image = '/ui/image/id/progress/stamp/'
    $C('pre').onerror = function () { this.src = blank; }
    $C('pre').onload  = function () { this.src = image + guid(); }
    $C('pre').src = image + guid();  
    connection.send();     
}
var shuffle = function(o){ //v1.0
	for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
};

function wall ()
{ //alert ('wall');
	var v = 0, exc = { };
	boxes = [];
    while (panes.length < 6 && panes.length < db.length)
    {
    	var r=Math.floor(Math.random()*db.length);
    	var name = db[r];
    	if (!exc[name])
    	{
    	    panes.push (name);
    	    exc[name] = name;
    	    boxes.push(v);
    	    v++;
    	}
    }
    shuffle(boxes);
    build();
}

function build()
{
	stamp ++;
	document.title = panes.length;
	if (panes.length > 0)
	{
		var pane = panes.pop();
		var key  = boxes.pop();
		var uri  = "/ui/image/group/" + pane + "/id/preview/stamp/" + stamp + '/box/' + key; 
		var url  = "/ui/commandhandler/request/group/group/" + pane;
		var url  = "/ui/commandhandler/request/lookup/side/front/index/" + key;
	    var box  = $C('box' + key), that = box.src;
	    box.onload  = function () 
	    { 
			this.onload = null;
			this.src = uri + '/static/on';
	    	this.onclick = function () { location.href = url }
	    	setTimeout(build, 500); 
	    }
	    box.onerror = function () { box.src = that; } //build(); } 
	    document.title = pane;
	    box.src  = uri; 
		return;
	}
	setTimeout (splash, 3000);
}

var parts;
function splash ()
{
	var r=Math.floor(Math.random()*db.length);
	var name = db[r], uri = "/ui/image/id/splash/group/" + name + '/stamp/' + guid(); 
    var sp = new Image(); 
    parts = []
    sp.onerror = function () { document.title = name; splash();}
    sp.onload  = function () {
    	for (var i=0,y=0;y<2;y++)
    	{
    		for (var x=0;x<3;x++)
    		{
//    			var box  = $C('box' + i);
    			var src = uri + '/coords/' + x + 'x' + y;// alert (src);
    			parts.push ({key:i, src:src, name:name})
    		//	box.src = src;
    			i ++;
    		//	return;
    		}
    	}
    	shuffle (parts);
    	impress()
    }
    sp.src = uri;
    enqueue();
}

function impress ()
{
	if (!parts.length) 
	{
		setTimeout (wall, 5000)
		return;
	}
//	var im = new Image();
	
	var part = parts.pop();
	var box  = $C('box' + part.key), that = box.src;
//	var url  = "/ui/commandhandler/request/group/group/" + part.name;
	var url  = "/ui/commandhandler/request/lookup/side/splash";
	box.onload = function () {
		this.onload = null;
		this.src = part.src + '/static/on';
    	this.onclick = function () { location.href = url; } 
    	setTimeout (impress, 500); 
    }
//	im.onload = function () { box.src = this.src;  }
	box.onerror = function () { echo(this.src); splash(); }
	box.src = part.src;
}
 
function echo (uri)
{
	var htm = '<a href="' + uri + '" target="_blank">' + uri + '</a>';
//	$C('header').innerHTML = htm;
}
















